import logging

from rest_framework import status
from rest_framework.permissions import IsAuthenticated

from users.utils import check_verify_email_token

logger = logging.getLogger("meiduo")
"""
实现注册功能
路径..../users/

"""
from rest_framework.generics import CreateAPIView, GenericAPIView, UpdateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from users.models import User
# .../usernames/(?P<username>\w{5, 20})/count/
from users.serializers import UserSerializer, EmailSerializer


# ＝＝＝＝＝＝＝＝＝＝＝＝各字段的存在判断＝＝＝＝＝＝＝＝＝
class UserNameCountAPIView(APIView):
    def get(self, request, username):
        count = None
        try:
            count = User.objects.filter(username=username).count()
        except Exception as e:
            logger.error(e)
        data = {
            "count": count,
            "username": username

        }
        return Response(data)

# ...mobile/(?P<mobile>1[3456789]\d{9}/)/count
class MobileCountAPIView(APIView):
    def get(self, request, mobile):
        # 尝试从数据库中获取用户
        count= None
        try:
            count = User.objects.filter(mobile=mobile).count()
        except Exception as e:
            logger.error(e)

        data = {
            "count": count,
            "mobile": mobile
        }

        return Response(data)

# ＝＝＝＝＝＝＝＝＝＝＝＝用户注册视图＝＝＝＝＝＝＝＝＝＝＝
class UserAPIView(CreateAPIView):

    serializer_class = UserSerializer


class ListUserCentreInfo(GenericAPIView):
    permission_classes = [IsAuthenticated]
    def get(self, request):
        # 判断用户是否登陆
        # print(request.META)
        user = request.user
        # print(user.is_authenticated)
        # print(user)
        print(user.is_checked)
        return Response({
            "id": user.id,
            "username": user.username,
            "mobile": user.mobile,
            "email": user.email,
            "email_active": user.is_checked
        })


class SetEmailView(UpdateAPIView):
    serializer_class = EmailSerializer
    permission_classes = [IsAuthenticated]

    def get_object(self, *args, **kwargs):
        return self.request.user


class VerifyEmailView(APIView):
    """更新邮箱激活状态视图"""
    def get(self, request):
        # 1. 获取token提取里面的user.id
        try:
            token = request.query_params.get("token")
        except Exception:
            return Response({"message": "无效的token"},status=status.HTTP_400_BAD_REQUEST)

        user_id = check_verify_email_token(token)
        if user_id is None:
            return Response({"message": "无效的token"}, status=status.HTTP_400_BAD_REQUEST)

        # 2. 根据id获取用户信息
        try:
            # pk 表示当前模型中的主键字段
            user = User.objects.get(pk=user_id)
        except:
            return Response({"message": "无效的token"}, status=status.HTTP_400_BAD_REQUEST)

        # 3. 修改用户的邮箱激活状态
        user.email_active = True
        user.save()

        # 4. 响应数据
        return Response({"message":"ok"},status=status.HTTP_200_OK)